<template>
	<view class="app-container">
		<!-- 自定义导航栏 -->
		<AdaptiveNavBar title="分类" text-color="#ffffff" />

		<!-- 搜索框 -->
		<view class="search-container" :style="{ marginTop: $navbarUtil.getNavbarTotalHeightRpx() }">
			<u-search placeholder="搜索资质" v-model="keyword" :showAction="false" @change="handleSearchChange" />
		</view>

		<!-- 列表 -->
		<view class="otherCertification-list">
			<view class="otherCertification-list-item" v-for="(item, idx) in filteredList" :key="idx"
				@tap="showPopup(item.name)">
				{{ item.name }}
			</view>

			<!-- 无结果提示 -->
			<view class="empty-tip" v-if="filteredList.length === 0">
				<text class="empty-text">暂无匹配的资质</text>
			</view>
		</view>

		<!-- 弹窗：资质上传 -->
		<u-popup :show="show" @close="close" mode="center" :safeAreaInsetBottom="false" :closeable="true"
			closeIconPos="top-right">
			<view class="popup-content">
				<!-- 头部：资质名称 -->
				<view class="popup-content-header">
					<view class="popup-content-header-lable">证照/资质类型*</view>
					<view class="popup-content-header-name">{{ formData.name }}</view>
				</view>

				<!-- 主体：图片上传 -->
				<view class="popup-content-body">
					<!-- 未上传时显示 + -->
					<view v-if="!formData.imageUrl" class="certification-img upload" @tap="chooseImage">
						<view class="upload-icon">+</view>
					</view>

					<!-- 已上传显示图片 -->
					<view v-else class="certification-img preview">
						<image :src="formData.imageUrl" mode="aspectFit" @tap.stop="previewImage" />
						<text class="delete-icon" @tap="deleteImage">X</text>
					</view>

					<view class="popup-content-desc">
						点击+上传证照/资质文件图片
					</view>
				</view>

				<!-- 底部：提交按钮 -->
				<view class="popup-content-footer">
					<view class="popup-content-btn" @tap="submitForm">
						保存并提交审核
					</view>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import {
		request,
		BASE_URL
	} from '@/utils/request.js';

	export default {
		data() {
			return {
				show: false, // 控制弹窗显示
				keyword: '', // 搜索关键词
				formData: {
					id: '',
					merchantId: '',
					name: '', // 资质名称
					imageUrl: '' // 图片路径（本地临时或服务器）
				},
				companyInfo: '',
				hasNewImage: false,
				isUpdate: false, // 👈 显式声明 isUpdate
				otherCertification: [{
						name: '旅行社责任险'
					},{
						name: '公众责任险'
					},{
						name: '公共场所卫生许可证'
					},
					{
						name: '办学许可证'
					},
					{
						name: '学校法人登记证书'
					},
					{
						name: '学校代码证'
					},
					{
						name: '研学旅行基地认证'
					},
					{
						name: '道路运输经营许可证'
					},
					{
						name: '旅游景区经营许可证'
					},
					{
						name: '文化场馆备案证明'
					},
					{
						name: '食品经营许可证'
					},
					{
						name: '高危险性体育项目经营许可证'
					},
					{
						name: '消防安全检查合格证'
					},
					{
						name: '管理员账号授权书'
					},
					{
						name: '品牌授权书或相关合作协议'
					},
					{
						name: '其他资质'
					}
				],
				searchTimer: null // 防抖定时器
			}
		},
		computed: {
			// 过滤后的列表
			filteredList() {
				const kw = this.keyword.trim();
				if (!kw) return this.otherCertification;
				return this.otherCertification.filter(item =>
					item.name.toLowerCase().includes(kw.toLowerCase())
				);
			}
		},
		onLoad() {
			this.companyInfo = uni.getStorageSync('companyInfo');
		},
		methods: {
			// 搜索输入处理（防抖）
			handleSearchChange() {
				if (this.searchTimer) clearTimeout(this.searchTimer);
				this.searchTimer = setTimeout(() => {
					console.log('搜索关键词:', this.keyword);
				}, 300);
			},

			// 显示弹窗
			async showPopup(name) {
				this.formData.name = name;
				await this.getCertificationInfo();
				this.show = true;
			},

			// 关闭弹窗
			close() {
				this.show = false;
				this.hasNewImage = false; // 关闭时重置标记
			},

			// 选择图片
			chooseImage() {
				uni.chooseMedia({
					count: 1,
					mediaType: ['image'],
					sourceType: ['album', 'camera'],
					success: (res) => {
						const tempFilePath = res.tempFiles[0].tempFilePath;
						this.formData.imageUrl = tempFilePath;
						this.hasNewImage = true; // 标记为新图
						console.log('图片选择成功:', this.formData);
					},
					fail: (err) => {
						console.error('选择图片失败:', err);
						uni.showToast({
							title: '选择图片失败',
							icon: 'none'
						});
					}
				});
			},

			// 删除图片
			deleteImage() {
				uni.showModal({
					title: '确认删除',
					content: '确定要删除这张图片吗？',
					success: (res) => {
						if (res.confirm) {
							this.formData.imageUrl = '';
							this.hasNewImage = false; // 图片删了，不再是新图
						}
					}
				});
			},

			// 预览图片
			previewImage() {
				if (!this.formData.imageUrl) return;

				uni.previewImage({
					urls: [this.formData.imageUrl],
					current: 0,
					fail: () => {
						uni.showToast({
							title: '无法预览该图片',
							icon: 'none'
						});
					}
				});
			},

			// 获取当前资质信息（判断是新增还是编辑）
			async getCertificationInfo() {
				try {
					const res = await request({
						url: `/merchantQualification?merchantId=${this.companyInfo.id}&name=${this.formData.name}`,
						method: 'GET',
						loading: true
					});

					console.log('当前证书信息:', res);
					if (res.code == 200) {
						if (res.data) {
							// 编辑状态
							this.isUpdate = true;
							this.formData.id = res.data.id;
							this.formData.imageUrl = res.data.imageUrl;
						} else {
							// 新增状态
							this.isUpdate = false;
							this.formData.imageUrl = '';
						}
					}

				} catch (err) {
					console.error('获取证书信息失败', err);
					uni.showToast({
						title: '加载失败',
						icon: 'none'
					});
				}
			},

			// 单文件上传到服务器
			uploadSingleFileToServer(file) {
				return new Promise((resolve, reject) => {
					uni.uploadFile({
						url: `${BASE_URL}/local-file/upload`,
						filePath: file,
						name: 'file',
						header: {
							'Authorization': uni.getStorageSync('accessToken') || ''
						},
						success: (uploadRes) => {
							try {
								const resData = JSON.parse(uploadRes.data);
								if (resData.code === 200) {
									resolve(resData);
								} else {
									reject(new Error(resData.msg || '上传失败'));
								}
							} catch (parseError) {
								reject(new Error('响应解析失败'));
							}
						},
						fail: (err) => {
							reject(err);
						}
					});
				});
			},

			// 提交表单
			// 提交表单
			async submitForm() {
				let finalImageUrl = '';

				// 情况1：用户删除了图片（imageUrl为空），且是编辑状态 → 调用删除接口
				if (!this.formData.imageUrl && this.isUpdate) {
					uni.showModal({
						title: '确认删除',
						content: `确定要删除【${this.formData.name}】这项资质吗？`,
						success: async (res) => {
							if (res.confirm) {
								try {
									const result = await request({
										url: `/merchantQualification/delete/${this.formData.id}`,
										method: 'DELETE',
										loading: true
									});

									if (result.code === 200) {
										uni.showToast({
											title: '删除成功'
										});
										this.close();
										// 可选：刷新列表
										// this.loadCertificationList();
									} else {
										uni.showToast({
											title: result.msg || '删除失败',
											icon: 'none'
										});
									}
								} catch (err) {
									console.error('删除资质失败:', err);
									uni.showToast({
										title: '删除失败',
										icon: 'none'
									});
								}
							}
						}
					});
					return; // 提前返回，不执行后续逻辑
				}
			

				// 情况2：有新图片，需要上传
				if (this.hasNewImage) {
					try {
						const uploadRes = await this.uploadSingleFileToServer(this.formData.imageUrl);
						if (uploadRes.code === 200) {
							finalImageUrl = uploadRes.data.url;
						} else {
							throw new Error(uploadRes.msg || '上传失败');
						}
					} catch (err) {
						console.error('图片上传失败:', err);
						uni.showToast({
							title: '图片上传失败',
							icon: 'none'
						});
						return;
					}
				} else {
					// 情况3：未更换图片，使用已有地址（可能是空，但不是删除操作）
					if(!this.formData.imageUrl){
						this.close()
						return
					}
					finalImageUrl = this.formData.imageUrl;
				}

				// 构造提交数据（新增或更新）
				const subForm = this.isUpdate ? {
					id: this.formData.id,
					imageUrl: finalImageUrl
				} : {
					merchantId: this.companyInfo.id,
					name: this.formData.name,
					imageUrl: finalImageUrl,
					sort: 1,
					status: 1
				};

				console.log('✅ 提交数据:', subForm);

				const result = await request({
					url: this.isUpdate ? `/merchantQualification/update` : '/merchantQualification/add',
					method: 'POST',
					data: subForm,
					loading: true
				});

				if (result.code === 200) {
					uni.showToast({
						title: this.isUpdate ? '编辑成功' : '新增成功'
					});
					this.close();
					this.hasNewImage = false;
				} else {
					uni.showToast({
						title: result.msg || (this.isUpdate ? '编辑失败' : '新增失败'),
						icon: 'none'
					});
				}
			}
		},
		// 页面销毁前清除定时器
		beforeDestroy() {
			if (this.searchTimer) {
				clearTimeout(this.searchTimer);
			}
		}
	}
</script>

<style scoped>
	.app-container {
		width: 100%;
		height: 100vh;
		background-color: #f8f8f8;
	}

	/* 搜索容器 */
	.search-container {
		padding: 16rpx 24rpx;
		background-color: #fff;
	}

	/* 列表样式 */
	.otherCertification-list {
		padding: 0 20px;
		margin-top: 16rpx;
		background-color: #fff;
		border-radius: 12rpx;
		overflow: hidden;
	}

	.otherCertification-list-item {
		padding: 12px 0;
		border-bottom: 1px solid #eee;
		font-size: 15px;
		color: #333;
	}

	.otherCertification-list-item:last-child {
		border-bottom: none;
	}

	/* 无结果提示 */
	.empty-tip {
		text-align: center;
		padding: 40px 0;
		color: #999;
		font-size: 14px;
	}

	/* 弹窗整体样式 */
	.popup-content {
		display: flex;
		flex-direction: column;
		border-radius: 10px;
		background-color: #fff;
		width: 350px;
		height: 350px;
	}

	/* 弹窗头部 */
	.popup-content-header {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 40px 20px 10px 20px;
		border-bottom: 1rpx solid #eee;
	}

	.popup-content-header-lable {
		font-size: 15px;
		font-weight: 500;
		color: #333;
	}

	.popup-content-header-name {
		padding: 5px 10px;
		border-radius: 5px;
		background-color: #f2f2f2;
		font-size: 14px;
		color: #666;
	}

	/* 图片区域 */
	.popup-content-body {
		flex: 1;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		gap: 10px;
	}

	.certification-img {
		width: 200px;
		height: 120px;
		border-radius: 10px;
		position: relative;

	}

	/* 上传状态 */
	.certification-img.upload {
		border: 1px dashed #ccc;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.upload-icon {
		font-size: 80rpx;
		color: #ccc;
	}

	/* 预览状态 */
	.certification-img.preview {
		border: none;
	}

	.certification-img image {
		width: 100%;
		height: 100%;
	}

	/* 删除按钮 */
	.delete-icon {
		position: absolute;
		top: -10rpx;
		right: -10rpx;
		width: 30rpx;
		height: 30rpx;
		padding: 5px;
		background-color: #f37b1d;
		color: #fff;
		font-size: 28rpx;
		border-radius: 50%;
		display: flex;
		justify-content: center;
		align-items: center;
		z-index: 10;
	}

	/* 描述文字 */
	.popup-content-desc {
		color: #999;
		font-size: 12px;
		text-align: center;
		margin-top: 5px;
	}

	/* 底部按钮 */
	.popup-content-footer {
		display: flex;
		justify-content: center;
		margin-bottom: 20px;
	}

	.popup-content-btn {
		width: 70%;
		text-align: center;
		border-radius: 10px;
		padding: 10px;
		color: #fff;
		background-color: #f37b1d;
		font-weight: 500;
	}
</style>